﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Configuration;
using System.Text;
using System.Text.RegularExpressions;
using System.IO.IsolatedStorage;

namespace RenRenClient
{
    public class OAuth
    {
        private IsolatedStorageSettings setting = IsolatedStorageSettings.ApplicationSettings;
        public string ApiKey { get; protected set; }
        public string SecretKey { get; protected set; }
        public string AccessToken
        {
            get
            {
                string value = "";
                if (setting.TryGetValue("OAuth.AccessToken", out value))
                {
                    return value;
                }
                else
                {
                    return null;
                }
                
            }
            protected set
            {
                setting["OAuth.AccessToken"] = value;
            }
        }
        public DateTime TokenExpire
        {
            get
            {
                DateTime value;
                if (setting.TryGetValue("OAuth.TokenExpire", out value))
                {
                    return value;
                }
                else
                {
                    return DateTime.Now;
                }
            }
            protected set
            {
                setting["OAuth.TokenExpire"] = value;
            }
        }

        public OAuth(string apiKey, string secretKey)
        {
            ApiKey = apiKey;
            SecretKey = secretKey;
        }

        public OAuth()
            : this("9a3c183879324ae28d9e88f61688b182", "320b6631192d4c40b2cd995a7dd85f6b")
        {
        }

        public string GetAuthURL()
        {
            StringBuilder url = new StringBuilder(RennURL.Authorize);
            url.AppendFormat("?client_id={0}", ApiKey);
            url.AppendFormat("&redirect_uri={0}", RennURL.LoginSuccess);
            url.AppendFormat("&response_type={0}", "token");
            url.AppendFormat("&display={0}", "touch");
            return url.ToString();
        }

        public void ParseToken(string returnURL)
        {
            var match = Regex.Match(returnURL, "access_token=([0-9%A-Za-z\\.-]+)&expires_in=([0-9]+)");
            if (match.Success)
            {
                AccessToken = match.Groups[1].Value.Replace("%7C", "|");
                int TokenExpiresIn = int.Parse(match.Groups[2].Value);
                TokenExpire = DateTime.Now.AddSeconds(TokenExpiresIn);
                setting.Save();
            }
        }

        public void EraseHistory()
        {
            setting.Remove("OAuth.AccessToken");
        }
    }
}
